#include "SwitchButton.h"



#include <QDebug>


SwitchButton::SwitchButton(QWidget *parent) : QWidget(parent)
{
    /* 创建指示器动画效果 */
    m_indicatorAnimation = new QPropertyAnimation(this);
    m_indicatorAnimation->setTargetObject(this);
    m_indicatorAnimation->setDuration(300);

    // 初始状态下的开始和结束位置
    m_indicatorAnimation->setStartValue(this->height() / 2);
    m_indicatorAnimation->setEndValue(this->width() - this->height() / 2);

    connect(m_indicatorAnimation, &QPropertyAnimation::valueChanged, this, [=](const QVariant& value) {
        m_indicatorPos.setX(value.toReal());
        update();
    });
}

SwitchButton::~SwitchButton()
{
    delete m_indicatorAnimation;
}

void SwitchButton::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);

    /* 绘制背景 */
    painter.setPen(Qt::NoPen);
    painter.setBrush(m_isOff ? m_offBgBrush : m_onBgBrush);
    painter.drawRoundedRect(this->rect(), this->height() / 2, this->height() / 2);

    /* 绘制指示器 */
    painter.setBrush(m_isOff ? m_offIndicatorBrush : m_onIndicatorBrush);
    painter.drawEllipse(m_indicatorPos, this->height() / 2 * 0.9, this->height() / 2 * 0.9);

    /* 绘制文字 */
    painter.setPen(m_textColor);
    painter.setFont(m_textFont);
    painter.drawText(this->rect(), Qt::AlignCenter, m_isOff ? m_offText : m_onText);
}

void SwitchButton::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        if (m_isOff)
        {
            m_indicatorAnimation->setDirection(QVariantAnimation::Forward);
            m_indicatorPos = QPointF(this->height() / 2, this->height() / 2); // 更新指示器位置
        }
        else
        {
            m_indicatorAnimation->setDirection(QVariantAnimation::Backward);
            m_indicatorPos = QPointF(this->width() - this->height() / 2, this->height() / 2);
        }

        m_indicatorAnimation->start();
        m_isOff = !m_isOff; // 更新开关状态
    }
}

void SwitchButton::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event);

    /* 设置指示器的位置 */
    m_indicatorPos = QPointF(this->height() / 2, this->height() / 2);

    /* 设置字体像素大小 */
    m_textFont.setPixelSize(this->height() * 0.2);

    QVariant startPos = m_isOff ? this->height() / 2 : this->width() - this->height() / 2;
    m_indicatorAnimation->setStartValue(startPos);

    QVariant endPos = m_isOff ? this->width() - this->height() / 2 : this->height() / 2;
    m_indicatorAnimation->setEndValue(endPos);
}

